<template>
  <a-modal v-model:visible="showModal" :title="pageTlt" class="modal-dialog-wrapper" unmount-on-close :mask-closable="false" width="700px">
    <a-form :model="form" style="width: 600px; max-height: 600px">
      <a-checkbox :default-checked="allchoose" @change="allChange">全选</a-checkbox>
      <a-tree
        v-if="authList.length > 0"
        :data="authList"
        checkable
        show-line
        blockNode
        multiple
        check-strictly
        v-model:checked-keys="authOrgIds"
        @check="checkIds"
      >
        <template #switcher-icon="node, { isLeaf }">
          <icon-caret-down v-if="!isLeaf" />
          <template v-if="isLeaf">
            <icon-user-group v-if="node.orgType == 2" />
            <icon-home v-else />
          </template>
        </template>
      </a-tree>
    </a-form>
    <template #footer>
      <a-space>
        <a-button @click="onClose">关闭</a-button>
        <a-button type="primary" @click="onConfirm" :ok-loading="okLoading">确认</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup>
  import { ref } from 'vue'
  // import { systemEdit, systemDetail, systemCodeDetail } from '@/api/system/system'
  // import { Message } from '@arco-design/web-vue'
  import { getSiteCarHouseKeepByOrgId } from '@/api/business/workorder'

  const showModal = ref(false)
  const pageTlt = ref('编辑') //标题
  const oldDataTrees = ref([]) //未处理的树
  const authList = ref([])
  const authOrgIds = ref([])
  const staffId = ref(null)
  const okLoading = ref(false)

  // 权限全选
  const allchoose = ref(false)
  const allChange = (e) => {
    if (e == true) {
      authOrgIds.value = []
      oldDataTrees.value.forEach((i) => {
        authOrgIds.value.push(i.id)
      })
    } else {
      authOrgIds.value = []
    }
  }

  const show = (auth, Ids, oldDataTree, staff) => {
    authList.value = auth
    authOrgIds.value = Ids
    oldDataTrees.value = oldDataTree
    showModal.value = true
    if (authOrgIds.value.length > 0) {
      if (authOrgIds.value.length == oldDataTrees.value.length) {
        allchoose.value = true //默认全选
      }
    }
    staffId.value = Number(staff)
  }

  const onClose = () => {
    showModal.value = false
  }

  const emit = defineEmits(['saveOrgIds'])

  const onConfirm = (done) => {
    if (!staffId.value) {
      emit('saveOrgIds', authOrgIds.value)
      showModal.value = false
      done()
      return
    }
    okLoading.value = true
    // 编辑的时候确认是否车管家，车管家不能选择机构权限
    getSiteCarHouseKeepByOrgId({ orgIdList: authOrgIds.value, staffId: staffId.value })
      .then(() => {
        emit('saveOrgIds', authOrgIds.value)
        showModal.value = false
        done()
      })
      .catch((err) => {
        console.log(err)
        okLoading.value = false
      })
  }

  const checkIds = (e) => {
    console.log(e)
  }

  defineExpose({
    show,
  })
</script>

<style lang="less" scoped></style>
